//
//  EmojiTextView.swift
//  EmojiKeyBoard
//
//  Created by macs on 15/11/21.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit

class EmojiTextView: UITextView {
    
    func fullText () -> String {
        
        
        //获取到属性文本并且遍历
        let attrStr = attributedText
        /**
         *enumerationRange: NSRange 要便利的范围
         NSAttributedStringEnumerationOptions 遍历选择
         [String : AnyObject] 返回结果
         NSRange 结果的位置
         */
         //创建可变文本接受文字和文本内容
        var strMM = String()
        attrStr.enumerateAttributesInRange( NSRange(location: 0, length: attrStr.length) , options: []) { (dict, range, _) -> Void in
            //print(dict["NSAttachment"])
            
            if let attach =  dict["NSAttachment"] as? EmojiAttachement {
                
                //图片文本
                let text = attach.chs
                
                strMM += text ?? ""
                
            } else {
                
                //文本
                let str = (attrStr.string as NSString).substringWithRange(range)
                
                strMM += str
                
            }
            
        }
        //print(strMM)
        return strMM
    }
    
    func insertAttrateText(emoji : Emoji) {
        if emoji.isEmpty {
            
            return
        }
        
        if emoji.isRemove {
            
            deleteBackward()
            return
        }
        
        if emoji.code != nil {
            replaceRange(selectedTextRange!, withText: emoji.codeString ?? "")
            return
        }
        
        let attachment = EmojiAttachement()
        
        //        attachment.image = UIImage(contentsOfFile: emoji.imagePath ?? "")
        //        //设置附件大小
        //        let lineHight = textView.font?.lineHeight
        //        attachment.bounds = CGRect(x: 0, y: -4, width: lineHight!, height: lineHight!)
        //        //将附件转为属性文本
        //        let imageText = NSAttributedString(attachment: attachment)
        
        let imageText = attachment.emojiGetImageText(emoji, font: font!)
        //获取 textView 属性文本
        //记录光标
        let range = selectedRange
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        //替换属性文本
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        attributedText = strM
        //设置光标
        selectedRange = NSMakeRange(range.location + 1, 0)
        
    }
    
}
